<template>
    <el-container>
        <el-container>
            <el-container>
                <el-main>
                    <!-- 搜索表单 -->
                    <el-form
                            :model="searchForm"
                            ref="searchform"
                            label-width="80px"
                            size="normal"
                    >
                        <el-row :gutter="5">
                            <el-col :span="6" :offset="0">
                                <el-form-item label="用户名">
                                    <el-input v-model="searchForm.username"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6" :offset="0">
                                <el-form-item label="用户电话">
                                    <el-input v-model="searchForm.mobile"></el-input>
                                </el-form-item>
                            </el-col>

                            <el-button type="primary" @click="search">查找</el-button>
                            <el-button type="primary" @click="addUser" v-if="isAdmin===1">新增</el-button>
                        </el-row>
                    </el-form>
                    <el-table :data="tableData" style="width: 100%" :height="tableHeight" stripe border>
                        <el-table-column label="行号" type="index" width="80" align="center"></el-table-column>
                        <el-table-column prop="username" label="用户名" width="180" align="center"></el-table-column>

                        <el-table-column prop="loginName" label="ID" width="180" align="center">
                        </el-table-column>
                        <el-table-column prop="mobile" label="手机号" width="180" align="center">
                        </el-table-column>
                        <el-table-column prop="role.name" label="角色" align="center" width="120">
                            <template slot-scope="scope">
                                <el-tag type="success">{{scope.row.role!=null && scope.row.role.name!=null ?
                                    scope.row.role.name :"无"}}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="isEnabled" label="是否可用" align="center" width="80">
                            <template slot-scope="scope">
                                <el-button :type="scope.row.isEnabled==='1' ? 'success' : 'warning'"
                                           :icon="scope.row.isEnabled==='1' ? 'el-icon-check' : 'el-icon-close'"
                                           circle></el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="status" label="状态" align="center" width="80">
                            <template slot-scope="scope">
                                <el-tag :type="scope.row.status==='正常' ? 'success' : 'warning'">{{scope.row.status}}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <!--            如果是管理员才能显示编辑页面-->
                        <el-table-column align="center" v-if="isAdmin===1" fixed="right" width="260" label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" size="mini" @click="editUser(scope.$index,scope.row)">编辑
                                </el-button>
                                <el-button type="success" size="mini" @click="assignRole(scope.$index,scope.row)">分配角色</el-button>
                                <el-button type="danger" size="mini" @click="deleteUser(scope.$index,scope.row)">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <!-- 分页 -->
                    <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="currentPage"
                            :page-sizes="[5, 10, 15, 20]"
                            :page-size="5"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="total"
                    >
                    </el-pagination>

                    <!-- 新增用户 -->
                    <el-dialog
                            :title="dialogTitle"
                            :visible.sync="dialogVisible"
                            width="45%"
                    >
                        <el-form
                                size="normal"
                                :model="addForm"
                                ref="addForm"
                                :rules="addrules"
                                label-width="80px"
                        >
                            <el-row :gutter="5">
                                <el-col :span="12" :offset="0">
                                    <el-form-item prop="loginName" label="显示ID">
                                        <el-input v-model="addForm.loginName"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12" :offset="0">
                                    <el-form-item prop="username" label="登录名">
                                        <el-input v-model="addForm.username"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row :gutter="5">
                                <el-col :span="12" :offset="0">
                                    <el-form-item prop="password" label="密码">
                                        <el-input
                                                show-password
                                                v-model="addForm.password"
                                        ></el-input>
                                    </el-form-item>
                                </el-col>

                                <el-col :span="12" :offset="0">
                                    <el-form-item prop="mobile" label="电话">
                                        <el-input v-model="addForm.mobile"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row :gutter="5">
                                <el-col :span="12" :offset="0">
                                    <el-form-item prop="status" label="状态">
                                        <el-select v-model="addForm.status" placeholder="请选择">
                                            <el-option
                                                    v-for="item in statusoptions"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value">
                                            </el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12" :offset="0">
                                    <el-form-item prop="isEnabled" label="启用/禁用">
                                        <el-radio v-model="addForm.isEnabled" label="1">启用</el-radio>
                                        <el-radio v-model="addForm.isEnabled" label="0">禁用</el-radio>
                                    </el-form-item>
                                </el-col>

                            </el-row>

                        </el-form>

                        <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="confirmUserSave">确 定</el-button>
            </span>
                    </el-dialog>

                    <!--分配角色-->
                    <el-dialog class="roleClass"
                               title="分配角色"
                               :visible.sync="roleDialogVisible"
                               width="50%"
                    >
                        <el-table ref="roleTable" @current-change="selectRoleRow" highlight-current-row
                                  :data="roleTableData" style="width: 100%">
                            <el-table-column prop="id" label="序号" width="180"></el-table-column>
                            <el-table-column prop="name" label="名称"></el-table-column>
                        </el-table>
                        <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmRoleSave">确 定</el-button>
      </span>
                    </el-dialog>
                </el-main>
            </el-container>
        </el-container>
    </el-container>
</template>

<script>
    import api from "../../../utils/axios/api";
    import dmzUtil from "../../../utils/DmzUtil";

    export default {
        name: "UserList",
        components: {},
        data() {
            return {
                // 分配角色窗口是否可见
                roleDialogVisible: false,
                // 角色表格数据
                roleTableData: [],
                addrules: {
                    loginName: [
                        {
                            required: true,
                            trigger: "change",
                            message: "请输入ID名称",
                        },

                    ],
                    username: [
                        {
                            required: true,
                            trigger: "change",
                            message: "请输入用户名",
                        },
                        {
                            validator: function (rule, value, callback) {
                                //  校验英文的正则
                                if (/[a-zA-z]$/.test(value) == false) {
                                    callback(new Error("请输入英文"));
                                } else {
                                    //校验通过
                                    callback();
                                }
                            },
                            trigger: "blur"
                        }
                    ],
                    mobile: [
                        {
                            required: true,
                            trigger: "change",
                            message: "请输入手机号",
                        },
                    ],
                    password: [
                        {
                            required: true,
                            trigger: "change",
                            message: "请输入密码",
                        },
                    ],

                },

                //分配用户的角色id
                roleId: '',
                //要分配角色的用户id
                selectUserId: '',
                //当前选中的行
                currentRow: "",
                //0 新增 1：编辑
                // 打开对话框的模式  0新增 1编辑
                editTag: 0,

                // 新增和编辑时的状态选项
                statusoptions: [
                    {value: 0, label: '正常'}, {value: 1, label: '观察'}, {value: 2, label: '冻结'}
                ],
                // 新增与编辑对话框标题
                dialogTitle: "新增用户",
                // 新增编辑对话框的显示属性
                dialogVisible: false,
                isAdmin: false,
                //   当前页码
                currentPage: 1,
                // 当前页数量
                pageSize: 5,
                // 数据总数量
                total: 0,

                // 新增用户数据模型
                addForm: {
                    id: 0,
                    loginName: "",
                    mobile: "",
                    username: "",
                    password: "",
                    status: 0,
                    isEnabled: "1"
                },

                // 表格查找的模型
                searchForm: {
                    username: "",
                    loginName: "",
                    mobile: "",
                },
                // 表格数据
                tableData: [],
                tableHeight: window.innerHeight - 330,
            };
        },
        methods: {
            //当前选择的角色
            selectRoleRow(row){
                this.currentRow = row;
                // console.log(row);
            },
            //分配角色保存
            async confirmRoleSave(){
                let _this = this;
                //获取参数
                let parm = {
                    userId:_this.selectUserId,
                    roleId:_this.currentRow.id
                }

                let {data:res} = await api.assingRole(parm);
                if(res.code == 0){
                    _this.$message({
                        message: res.msg,
                        type: "success"
                    });
                    //把选中的行取消
                    _this.$refs.roleTable.setCurrentRow();
                    _this.roleDialogVisible = false;//关闭弹框
                    _this.getUserList();
                }
            },
            //分配角色获取数据列表
            async getRolistForAssing(){
                let {data:res} = await api.getRolistForAssing();
                if(res.code == 0){
                    this.roleTableData = res.data;
                }
            },

            // 获取当前用户已经分配的角色
            async getRoleIdByUserId(userId){
                let parm ={
                    userId:userId
                }
                let {data:res} = await api.getRoleIdByUserId(parm);
                if(res.code == 0){
                    if(res.data){
                        this.roleId = res.data.roleId;
                    }
                }
            },
// 分配角色
            async assignRole(index, row) {
                let _this = this;
                _this.roleId = '';
                //设置分配角色的用户id
                _this.selectUserId = row.id;
                _this.roleDialogVisible = true;
                await _this.getRoleIdByUserId(row.id);
                _this.$nextTick(function(){
                    _this.$refs.roleTable.setCurrentRow();
                    for(let i = 0;i < _this.roleTableData.length;i++){
                        if(_this.roleId == _this.roleTableData[i].id){
                            //设为选中
                            _this.$refs.roleTable.setCurrentRow(_this.roleTableData[i]);
                            _this.currentRow = _this.roleTableData[i];
                        }
                    }
                })
            },


            // 删除用户
            deleteUser(index, row) {
                let param = {
                    id: row.id
                }
                let _this = this;
                _this.$confirm("确定删除吗 ?", "系统提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(async () => {
                    let {data: res} = await api.deleteUserById(param);
                    if (res.code == 0) {
                        _this.$message({
                            message: res.msg,
                            type: 'success'
                        })
                        _this.getUserList();
                        _this.dialogVisible = false;
                    }
                    console.log(row);
                })

            },
            // 编辑用户按钮
            async editUser(index, row) {
                let _this = this;
                _this.resetForm("addForm");
                _this.editTag = 1;
                _this.dialogVisible = true;
                _this.dialogTitle = "编辑用户";
                let param = {
                    id: row.id
                }
                let {data: res} = await api.getUserById(param);
                if (res.code == 0) {
                    _this.addForm.id = res.data.id;
                    _this.addForm.loginName = res.data.loginName;
                    _this.addForm.username = res.data.username;
                    _this.addForm.password = res.data.password;
                    _this.addForm.status = res.data.status;
                    _this.addForm.isEnabled = res.data.isEnabled;
                    _this.addForm.mobile = res.data.mobile;
                }

            },
            // 新增用户
            addUser() {
                this.dialogTitle = "新增用户";
                this.dialogVisible = true;
                this.editTag = 0;
            },

            //   处理当前页面变化函数
            handleCurrentChange(val) {
                this.currentPage = val;
                this.getUserList();
            },
            //   处理分页数据变化函数
            handleSizeChange(val) {
                this.pageSize = val;
                this.getUserList();
            },
            //   处理树初始化后的函数
            handleTreeCreated(treeObj) {
                this.ztreeObj = treeObj;
                treeObj.expandAll(true);
            },
            //   找到用户
            search() {
                this.getUserList();
            },
            // 新增用户
            confirmUserSave() {

                let _this = this;
                let res = null
                _this.$refs.addForm.validate(async (valid) => {
                    if (valid) {
                        let param = {
                            id: _this.addForm.id,
                            username: _this.addForm.username,
                            loginName: _this.addForm.loginName,
                            password: _this.addForm.password,
                            mobile: _this.addForm.mobile,
                            status: _this.addForm.status,
                            isEnabled: _this.addForm.isEnabled
                        }
                        if (_this.editTag == 0) {
                            res = await api.addNewUser(param);
                        }
                        if (_this.editTag == 1) {
                            res = await api.editUserInfo(param);
                        }
                        let data = res.data;
                        if (data.code == 0) {
                            _this.$message({
                                type: 'success',
                                message: data.msg
                            })
                            _this.dialogVisible = false;
                            _this.getUserList();
                        }
                    }

                })
            },

            resetForm(formName) {
                if (this.$refs[formName]) {
                    this.$refs[formName].resetFields();
                }
            },
            // 获取当前用户列表
            async getUserList() {
                let _this = this;
                _this.resetForm("searchform");
                let param = {
                    username: _this.searchForm.username,
                    mobile: _this.searchForm.mobile,
                    currentPage: _this.currentPage,
                    pageSize: _this.pageSize
                }
                let {data: res} = await api.getUserList(param);
                if (res.code == 0) {
                    _this.tableData = res.data.records;
                    _this.currentPage = res.data.current;
                    _this.pageSize = res.data.size;
                    _this.total = res.data.total;
                }
                // 转换用户的状态 0正常 1观察 2冻结
                for (var i = 0; i < _this.tableData.length; i++) {
                    if (_this.tableData[i].status === 0) {
                        this.tableData[i].status = '正常'
                    } else if (_this.tableData[i].status === 1) {
                        _this.tableData[i].status = '观察'
                    } else if (_this.tableData[i].status === 2) {
                        _this.tableData[i].status = '冻结'
                    }
                }

            }
        },
        mounted() {
            this.$nextTick(() => {
                this.tableHeight = window.innerHeight - 330; //后面的50：根据需求空出的高度，自行调整
            });
        },
        created() {
            this.getUserList();
            this.getRolistForAssing();
            // 获取当前用户信息是否是管理员
            this.isAdmin = dmzUtil.getSession('userInfo').isAdmin;
        }
    };
</script>

<style scoped>
    .el-main {
        padding-top: 5px;

        border-left: 1px solid #cccccc;
    }

    .el-aside {
        padding-left: 10px;
    }
</style>